<script setup lang="ts">
import YkShowDraw from '@yk/components/draw/show-draw/YkShowDraw.vue'
import { Cell, Graph } from '@antv/x6'
import { ConfigurationDTO } from '@/api/entity/self-config'
import { getSelfConfigByIdAPI } from '@/api/self-config'
import { getRealDataByIdsAPI } from '@/api/realtime'
import { FnOperationControl } from '@utils/object-util/periodic-execution/FnOperationControl'

const props = defineProps<{
  selfId: string
}>()

const emits = defineEmits(['load'])

// const _jsonData = '{"cells":[{"position":{"x":-4.774847184307873e-12,"y":1.000444171950221e-11},"size":{"width":1920,"height":1090},"view":"vue-shape-view","attrs":{"fo":{"class":"disable-event--pointer-events"}},"shape":"AMapC","data":{"dataConfig":{},"interactingSelect":{"disableDefaultMovable":true,"disableSelect":true,"disableEvent":true},"expose":{}},"id":"97693e79-1e39-4751-a82e-57180cd89b39","zIndex":1},{"position":{"x":3.410605131648481e-13,"y":7.105427357601002e-15},"size":{"width":1920,"height":80},"attrs":{"image":{"href":"http://localhost:5166/src/@yk/components/draw/editor-draw/library/images/modules/panel/images/%E9%9D%A2%E6%9D%BF-13.svg","class":"disable-event--pointer-events"}},"visible":true,"shape":"BaseImage","data":{"attrRoot":"image","interactingSelect":{"disableDefaultMovable":false,"disableSelect":true,"disableEvent":true}},"ports":{"groups":{"groupCenter":{"attrs":{"circle":{"name":"stroke","magnet":true,"opacity":0.2,"r":8}},"position":{"name":"line","args":{"start":{"x":0,"y":0},"end":{"x":"100%","y":"100%"}}}}},"items":[{"group":"groupCenter","id":"27e2b545-3d9a-4e4c-b85c-0e481f1618a4"}]},"id":"7c50a389-af9d-4a85-8cb0-6333a19ec91c","zIndex":2},{"position":{"x":20,"y":130},"size":{"width":480,"height":330},"attrs":{"image":{"href":"http://localhost:5166/src/@yk/components/draw/editor-draw/library/images/modules/panel/images/%E9%9D%A2%E6%9D%BF-8.svg","class":"disable-event--pointer-events"}},"visible":true,"shape":"BaseImage","data":{"attrRoot":"image","interactingSelect":{"disableDefaultMovable":false,"disableSelect":true,"disableEvent":true}},"ports":{"groups":{"groupCenter":{"attrs":{"circle":{"name":"stroke","magnet":true,"opacity":0.2,"r":8}},"position":{"name":"line","args":{"start":{"x":0,"y":0},"end":{"x":"100%","y":"100%"}}}}},"items":[{"group":"groupCenter","id":"655eb0cd-c5c5-471d-b5be-4ae6c467b91b"}]},"id":"c8faf840-bada-4f6f-af26-ec53a6c22739","zIndex":4},{"position":{"x":20,"y":520},"size":{"width":480,"height":330},"attrs":{"image":{"href":"http://localhost:5166/src/@yk/components/draw/editor-draw/library/images/modules/panel/images/%E9%9D%A2%E6%9D%BF-8.svg","class":"disable-event--pointer-events"}},"visible":true,"shape":"BaseImage","data":{"attrRoot":"image","interactingSelect":{"disableDefaultMovable":false,"disableSelect":true,"disableEvent":true}},"ports":{"groups":{"groupCenter":{"attrs":{"circle":{"name":"stroke","magnet":true,"opacity":0.2,"r":8}},"position":{"name":"line","args":{"start":{"x":0,"y":0},"end":{"x":"100%","y":"100%"}}}}},"items":[{"group":"groupCenter","id":"655eb0cd-c5c5-471d-b5be-4ae6c467b91b"}]},"id":"717297ef-7aea-4f74-beb4-09fbf5cdaef5","zIndex":5},{"position":{"x":1410,"y":130},"size":{"width":480,"height":330},"attrs":{"image":{"href":"http://localhost:5166/src/@yk/components/draw/editor-draw/library/images/modules/panel/images/%E9%9D%A2%E6%9D%BF-8.svg","class":"disable-event--pointer-events"}},"visible":true,"shape":"BaseImage","data":{"attrRoot":"image","interactingSelect":{"disableDefaultMovable":false,"disableSelect":true,"disableEvent":true}},"ports":{"groups":{"groupCenter":{"attrs":{"circle":{"name":"stroke","magnet":true,"opacity":0.2,"r":8}},"position":{"name":"line","args":{"start":{"x":0,"y":0},"end":{"x":"100%","y":"100%"}}}}},"items":[{"group":"groupCenter","id":"655eb0cd-c5c5-471d-b5be-4ae6c467b91b"}]},"id":"4c2d9a2d-0da8-465c-81a2-ba6d2dc55d81","zIndex":6},{"position":{"x":1410,"y":520},"size":{"width":480,"height":330},"attrs":{"image":{"href":"http://localhost:5166/src/@yk/components/draw/editor-draw/library/images/modules/panel/images/%E9%9D%A2%E6%9D%BF-8.svg","class":"disable-event--pointer-events"}},"visible":true,"shape":"BaseImage","data":{"attrRoot":"image","interactingSelect":{"disableDefaultMovable":false,"disableSelect":true,"disableEvent":true}},"ports":{"groups":{"groupCenter":{"attrs":{"circle":{"name":"stroke","magnet":true,"opacity":0.2,"r":8}},"position":{"name":"line","args":{"start":{"x":0,"y":0},"end":{"x":"100%","y":"100%"}}}}},"items":[{"group":"groupCenter","id":"655eb0cd-c5c5-471d-b5be-4ae6c467b91b"}]},"id":"68e3e429-ff05-4052-be73-0374eb060669","zIndex":7},{"position":{"x":29.999999999999318,"y":140.00000000000125},"size":{"width":460,"height":300},"view":"vue-shape-view","attrs":{"body":{"style":{"backgroundColor":"rgba(4, 29, 82, 0.36)"}}},"shape":"LineChart","data":{"dataConfig":{"echartsOptions":{"legend":{"show":true},"tooltip":{"show":true},"toolbox":{"show":false},"series":[{"itemStyle":{"color":"#5470C6"}}]},"echartsConfig":{"textColor":{"color":"#FFFFFF"},"splitLine":{"color":"#4C597E"},"area":{"show":true,"color":null}}},"expose":{}},"id":"4b8ed4e4-cb47-4123-b403-080b66c9e5cb","zIndex":8},{"position":{"x":1420,"y":146},"size":{"width":460,"height":300},"view":"vue-shape-view","attrs":{"body":{"style":{"backgroundColor":"rgba(4, 29, 82, 0.36)"}}},"shape":"LineChart","data":{"dataConfig":{"echartsOptions":{"legend":{"show":true},"tooltip":{"show":true},"toolbox":{"show":false},"series":[{"itemStyle":{"color":"#F17F2E"}}]},"echartsConfig":{"textColor":{"color":"#FFFFFF"},"splitLine":{"color":"#4C597E"},"area":{"show":true,"color":null}}},"expose":{}},"id":"3724200d-fdda-4604-80f4-e15eeaef2ab8","zIndex":10},{"position":{"x":1420,"y":534},"size":{"width":460,"height":300},"view":"vue-shape-view","attrs":{"body":{"style":{"backgroundColor":"rgba(4, 29, 82, 0.36)"}}},"shape":"LineChart","data":{"dataConfig":{"echartsOptions":{"legend":{"show":true},"tooltip":{"show":true},"toolbox":{"show":false},"series":[{"itemStyle":{"color":"#5470C6"}}]},"echartsConfig":{"textColor":{"color":"#FFFFFF"},"splitLine":{"color":"#4C597E"},"area":{"show":false}}},"expose":{}},"id":"c01d0cc6-718b-47ae-baef-40d2a8358bf3","zIndex":11},{"position":{"x":29.99999999999943,"y":530.0000000000011},"size":{"width":460,"height":310},"view":"vue-shape-view","attrs":{"body":{"style":{"backgroundColor":"rgba(4, 29, 82, 0.36)"}}},"shape":"BarChart","data":{"dataConfig":{"echartsOptions":{"legend":{"show":true},"tooltip":{"show":true},"toolbox":{"show":false}},"echartsConfig":{"textColor":{"color":"#FFFFFF"},"splitLine":{"color":"#EDEEF1"},"area":{"show":true,"color1":"#89EB6C","color2":null}}},"expose":{}},"id":"e93bedf7-66e0-43c1-9ea8-f9a5a5cb991a","zIndex":12},{"position":{"x":630,"y":10},"size":{"width":660,"height":60},"attrs":{"body":{"fill":"rgba(0, 0, 0, 0)"},"label":{"style":{"fontSize":40,"color":"rgba(35, 219, 225, 1)","fontWeight":"bold"},"text":"数据统计"}},"visible":true,"shape":"TextBox","data":{"attrRoot":["foreignObject","rect"],"interactingSelect":{"disableDefaultMovable":false,"disableSelect":false,"disableEvent":false}},"id":"e67d92bc-eafe-4fe8-a333-f1410f922d75","zIndex":13}],"size":{"width":1920,"height":1080},"background":{"size":"100% 100%"}}'
// const jsonData = JSON.parse(_jsonData)
onMounted(() => {
  getSelfJsonData()
})

// region TODO 全局变量
let sceneId = null
// endregion

// region TODO 获取组态数据
const selfJsonData = shallowRef<Record<string, any>>(null)
const selfConfig = shallowRef<ConfigurationDTO>()
function getSelfJsonData () {
  getSelfConfigByIdAPI({ id: props.selfId }).then((res) => {
    res.result().then((rdata) => {
      sceneId = rdata.data.groupId
      selfJsonData.value = JSON.parse(rdata.data.value || '{ size: { width: 800, height: 600 } }')
      selfConfig.value = rdata.data
    })
  })
}
// endregion

function load (graph: Graph) {
  const cells = graph.getCells()

  for (let i = 0, len = cells.length; i < len; i++) {
    const cell = cells[i]
    console.log(cell)
    // 过滤掉不能绑定数据
    if (!cell.data?.dataConfig) continue
    const dataConfig = cell.data.dataConfig
    // 过滤掉没有配置数据的
    switch (dataConfig.runModel) {
      case 'variableValue':
        const result = Boolean(dataConfig.variableAddress)
        if (result) addVariableDataCell(cell)
        break
      case 'selfRun':
        setTimeout(() => {
          dataConfig.run(cell, { sceneId })
        }, 500)
        break
    }
  }
  emits('load')
  initDataPool()
}

// region TODO 获取实时数据 - 适用与标准的设备-变量型的组件
function initDataPool () {
  useDeviceIds = Array.from(useDeviceSet)
  // 处理设备id是否还存在当前场景 ----------------------------
  // 如果不需要查询就不运行了
  if (useDeviceIds.length) variableDataOperationControl.run()
}

const variableCells = []
// 记录数据（设备#变量）与Cell的关系如{ 设备Id#变量Id: [Cell, Cell, ...] }
const variableDataDic: Record<string, Cell[]> = {}
const variableDataMap: Map<Cell, string> = new Map<Cell, string>()
// 添加需要适用实时数据的Cell
function addVariableDataCell (cell: Cell) {
  const { deviceId, variableAddress } = cell.data.dataConfig
  variableCells.push(cell)
  useDeviceSet.add(deviceId)
  const key = `${deviceId}#${variableAddress}`
  if (!variableDataDic[key]) variableDataDic[key] = []
  variableDataDic[key].push(cell)
  variableDataMap.set(cell, key)
}

// region TODO 获取实时变量数据
const useDeviceSet = new Set()
let useDeviceIds = []
const variableDataOperationControl = new FnOperationControl({ fn: loadDataPool, rightRun: true, timeout: 5000, pause: true })
async function loadDataPool () {
  return getRealDataByIdsAPI({
    deviceIds: useDeviceIds
  }).then((res) => {
    res.result().then((rdata) => {
      const data = Object.entries(rdata.data || {})
      const dataPool = {}
      // 处理数据
      for (let i = 0, len = data.length; i < len; i++) {
        let [deviceId, variables] = data[i]
        variables ??= {} as any
        variables.variableData ??= []
        for (let j = 0, len = variables.variableData.length; j < len; j++) {
          const variable = variables.variableData[j]
          const key = `${deviceId}#${variable.address}`
          dataPool[key] = variable
        }
      }
      // 渲染
      for (let i = 0, len = variableCells.length; i < len; i++) {
        const cell = variableCells[i]
        cell.data.dataConfig.updateData(cell, dataPool[variableDataMap.get(cell)] || {})
      }
    })
  })
}
onUnmounted(() => {
  variableDataOperationControl.stop()
})
// endregion
// endregion

</script>

<template>
  <yk-show-draw v-if="selfJsonData" :json-data="selfJsonData as any" @load="load" />
</template>

<style scoped lang="scss">

</style>
